<template>
  <div id="Params">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon title="注意:只允许为第三级分类设置相关参数" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
          v-model="selectedKeys"
          :options="catelist"
          :props="cascaderProps"
          @change="parentCateChanged">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- Tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button @click="addDialogVisible = true" :disabled="isBtnDisabled" type="primary" size="mini">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" :closable="true" @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditDialog(scope.row)" size="mini" icon="el-icon-edit" type="primary">编辑</el-button>
                <el-button @click="removeParams(scope.row.attr_id)" size="mini" icon="el-icon-delete" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="addDialogVisible = true" :disabled="isBtnDisabled" type="primary" size="mini">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" :closable="true" @close="handleClose(i, scope.row)">
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditDialog(scope.row)" size="mini" icon="el-icon-edit" type="primary">编辑</el-button>
                <el-button @click="removeParams(scope.row.attr_id)" size="mini" icon="el-icon-delete" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%" @close="addDialogClosed"
      >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClosed"
      >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getHttpParentCateList  } from 'network/cate'
import { getHttpParamsData, postHttpAddParams, putHttpEditParams, deleteHttpDeleteParamsById, putHttpAddAttrVals   } from 'network/params'
import { attrnameVf } from 'common/js/validator'
export default {
  name: "Params",
  data() {
    return {
      //商品分类列表
      catelist: [],
      //级联菜单的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true //是否运行选择一级分类
      },
      //级联选择器选中的值
      selectedKeys: [],
      //被激活页签的名称
      activeName: 'many',
      //动态参数的数据
      manyTableData: [],
      //静态参数的数据
      onlyTableData: [],
      //控制对话框显示隐藏
      addDialogVisible: false,
      //from表单
      addForm: {
        id: 0,
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      },
      //表单验证对象
      addFormRules: {
        attr_name: attrnameVf
      },
      //控制修改对话框的显示与隐藏
      editDialogVisible: false,
      editForm: {
        id: 0,
        attrId: 0,
        attr_name: '',
        attr_sel: ''
      },
      //表单验证对象
      editFormRules: {
        attr_name: attrnameVf
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取分类数据
    getCateList() {
      getHttpParentCateList(3).then(res => {
        if( res.meta.status !== 200) {         
          this.$message.error(res.meta.msg)
          return
        }
        else {
          this.catelist = res.data
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    //级联选择器选中的值发生变化触发的事件
    parentCateChanged() {
      this.getParamsData()
    },
    //页签点击事件
    handleTabClick() {
      this.getParamsData()
    },
    //获取参数列表数据
    getParamsData() {
      //证明选中的不是三级分类
      if(this.selectedKeys.length !== 3) {
        this.$message.error('只允许选择3级分类')
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      else {
        //当选中的是3级分类
        getHttpParamsData(this.cateId, this.activeName).then(res => {
          if( res.meta.status !== 200) {         
            this.$message.error(res.meta.msg)
            return
          }
          else {
            //将参数列表用空格分解为数组
            //"49吋4K超薄曲面 人工智能,55吋4K观影曲面 30核HDR,55吋4K超薄曲面 人工智能,65吋4K超薄曲面 人工智能"
            res.data.forEach(item => {
              //如果字符串为空就返回空数组，都在按空格分割数组
              item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
              //为新增tag的文本框Model和控制和隐藏文本框的属性添加 两个属性
              item.inputVisible = false
              item.inputValue = ''
            })
            if ( this.activeName === 'many' ) {
              this.manyTableData = res.data
            }
            else {
              this.onlyTableData = res.data
            }
          }
        }).catch(err => {
          this.$message.error(err)
        })
      }
    },
    //添加对话框关闭事件
    addDialogClosed() {
      //重置对话框
      this.$refs.addFormRef.resetFields()
    },
    //添加确定按钮事件
    addParams() {
      this.$refs.addFormRef.validate(valid => {
        if(!valid) {
          return
        }
        else {
          this.addForm.id = this.cateId
          this.addForm.attr_sel = this.activeName
          postHttpAddParams(this.addForm).then(res => {
            if( res.meta.status !== 201) {
              this.$message.error(res.meta.msg)
              return
            }
            else {
              this.$message.success(res.meta.msg)
              this.getParamsData()
              this.addDialogVisible = false
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
      })
    },
    //修改属性单击事件 展示修改的对话框
    showEditDialog(row) {
      this.editDialogVisible = true
      this.editForm.id = row.cat_id
      this.editForm.attrId = row.attr_id
      this.editForm.attr_name = row.attr_name
      this.editForm.attr_sel = row.attr_sel
    },
    //修改对话框的关闭事件
    editDialogClosed() {
      //重置对话框
      this.$refs.editFormRef.resetFields()
    },
    //编辑对话框确定事件
    editParams() {
      this.$refs.editFormRef.validate(valid => {
        if(!valid) {
          return
        }
        else {
          putHttpEditParams(this.editForm).then(res => {
            if( res.meta.status !== 200 ) {
              this.$message.error(res.meta.msg)
              return
            }
            else {
              this.$message.success(res.meta.msg)
              this.getParamsData()
              this.editDialogVisible = false
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
      })
    },
    //列表框删除单击事件
    removeParams(attr_id) {
      //弹窗询问用户是否删除数据
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteHttpDeleteParamsById(this.cateId, attr_id).then(res => {
          if( res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
            return
          }
          else {
            this.$message({type: 'success', message: '删除成功!' })
            this.getParamsData()
          }
        }).catch(err => {
          this.$message.error(err)
        })
        
      }).catch(() => {
        this.$message({ type: 'info',message: '已取消删除' })          
      })
    },
    //新增tag的文本框失去焦点及按回车键的事件触发函数
    handleInputConfirm(row) {
      if(row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      }
      else {
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        //发起网络请求
        this.saveAttrVals(row)
      }
    },
    //新增tag标签鼠标点击新增按钮的事件
    showInput(row) {
      row.inputVisible = true
      //让文本框自动获得焦点
      //$nextTick 方法的作用，就是当页面上的元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //tag标签关闭事件
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      //发起网络请求
      this.saveAttrVals(row)
    },
    //将对attr_vals的操作保存到数据库
    saveAttrVals(row) {
      putHttpAddAttrVals(this.cateId,row.attr_id,row.attr_name,row.attr_sel,row.attr_vals.join(' ')).then(res => {
        if( res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return
        }
        else {
          this.$message.success(res.meta.msg)
        }
      }).catch(err => {
        this.$message.error(err)
      })
    }
  },
  //计算属性
  computed: {
    //如果按钮需要被禁用，则返回True,否则返回False
    isBtnDisabled() {
      if ( this.selectedKeys.length !== 3) {
        return true
      }
      else {
        return false
      }
    },
    //当前选中的三级分类的id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      else {
        return null
      }
    },
    //动态计算标题的文本
    titleText() {
      if ( this.activeName === 'many') {
        return '动态参数'
      }
      else {
        return '静态属性'
      }
    }
  }
}
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
